<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="formData.username" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="formData.email" />
    </el-form-item>
    <el-form-item label="角色" prop="role" v-if="dialogType === 'edit'">
      <el-select v-model="formData.role">
        <el-option label="管理员" value="admin" />
        <el-option label="普通用户" value="user" />
      </el-select>
    </el-form-item>
    <el-form-item label="状态" prop="status" v-if="dialogType === 'edit'">
      <el-switch
        v-model="formData.status"
        :active-value="'enabled'"
        :inactive-value="'disabled'"
      />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="formData.password" type="password" show-password />
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { inject, reactive, ref } from "vue";
import type { UserInfo } from "@/types";
import { ElMessage, type FormInstance } from "element-plus";
import { editProfile, register } from "@/api/user";
const emits = defineEmits(["success", "error"]);
const dialogType = inject("dialogType", ref<"add" | "edit">("add"));
const formRef = ref<FormInstance | null>(null);
const outData = inject("formData", ref<Partial<UserInfo>>());
const formData = reactive<Partial<UserInfo>>({
  username: undefined,
  email: undefined,
  role: undefined,
  status: undefined,
  password: undefined,
});
if (outData.value) {
  Object.assign(formData, outData.value);
}
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
};

const submit = async () => {
  try {
    await formRef.value?.validate();
    const { id, createdAt, updatedAt, ...user } = formData;
    if (dialogType.value === "add") {
      // 这里应该调用添加API
      register({
        password: user.password!,
        confirmPassword: user.password!,
        username: user.username!,
        email: user.email!,
      })
        .then((res) => {
          emits("success");
        })
        .catch((err) => {
          emits("error");
        });
    } else {
      // 这里应该调用添加/编辑API
      editProfile(id!, user)
        .then((res) => {
          emits("success");
        })
        .catch((err) => {
          emits("error");
        });
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

defineExpose({
  submit,
});
</script>
